#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
from datetime import datetime
from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility
from extension.test_logic.RequestBase import RequestBase


class REDFISH_USER_004(Case):
    """
        Name:
            REDFISH_USER_004
        Label:
            修改指定用户信息
        PreCondition:
            BMC web service normal
        TestStep:
            1) 修改新增用户信息 PATCH https://BMC_IP/redfish/v1/AccountService/Accounts/account_id body里添加{"RoleId":"Operator"}需要从get获取If-Match: ETag_value在patch里添加
        ExpectedResult:
            A) 执行响应码为200,查看更改用户权限（与iBMC-用户&安全- 本地用户，用户信息权限更改和实际一致）
        Parameters:

        Author:
            baixin liuya
        Last Modified:

        Remark:

    """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.bmc_host = self.device_dut.get_host(host_type=HostType.BMC)
        self.bmc_ip = self.bmc_host.local_ip
        self.bmc_user = self.bmc_host.username
        self.bmc_pwd = self.bmc_host.password

        self.logger.info("获取Token")
        self.request = RequestBase(self.bmc_ip, self.bmc_user, self.bmc_pwd)
        return_code, session_id = self.request.create_session()
        self.assertIsNotNone(return_code)
        self.session_id = session_id

    # 测试步骤
    def procedure(self):
        dst_url = "/redfish/v1/AccountService/Accounts"
        resp = self.request.get(dst_url)
        self.assertIsNotNone(resp[0])
        content = resp[1]
        self.logger.info(f"接口[{dst_url}]返回值：\n{json.dumps(content, indent=4, ensure_ascii=False)}")
        user_count = content['Members@odata.count']
        self.log_step(f"Step1: 查询当前用户数：{user_count}")

        self.log_step("Step2: 创建新用户")
        dst_url = "/redfish/v1/AccountService/Accounts"
        _time_str = datetime.now().strftime("%H%M%S")
        new_user = f"user{_time_str}"
        json_text = {"UserName": f"{new_user}", "Password": "100trust.", "RoleId": "Administrator"}
        resp = self.request.post(url=dst_url, params=json_text)
        rc = resp[0]
        self.assertIsNotNone(rc)
        if rc != 201:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是201，实际返回码{rc}")
        content = resp[1]
        self.logger.info(f"接口[{dst_url}]返回值：\n{json.dumps(content, indent=4, ensure_ascii=False)}")

        dst_url = "/redfish/v1/AccountService/Accounts"
        resp = self.request.get(dst_url)
        self.assertIsNotNone(resp[0])
        content = resp[1]
        self.logger.info(f"接口[{dst_url}]返回值：\n{json.dumps(content, indent=4, ensure_ascii=False)}")
        user_count = content['Members@odata.count']
        self.log_step(f"Step3: 最新用户数：{user_count}")

        user_dict = {}
        for i in range(user_count):
            user_name = content['Members'][i]['UserName']
            user_id = content['Members'][i]['Id']
            user_dict[user_name] = user_id
        # get if-match
        new_user_id = user_dict[new_user]
        url = f"/redfish/v1/AccountService/Accounts/{new_user_id}"
        header = self.request.get_header(url)
        self.assertIsNotNone(header)
        if_match_str = header['ETag']
        self.request.headers['If-Match'] = if_match_str

        self.log_step(f"Step4: 修改新创建的用户：{new_user}操作权限")
        json_text = {"RoleId": "Operator"}
        patch_url = f"{dst_url}/{new_user_id}"
        resp = self.request.patch(url=patch_url, params=json_text)

        rc = resp[0]
        self.assertIsNotNone(rc)
        content = resp[1]
        self.logger.info(f"修改{new_user}后，回显信息：\n{json.dumps(content, indent=4)}")

        self.log_step(f"Step5: 删除新创建的用户：{new_user}")
        del_url = dst_url
        resp = self.request.delete(del_url, f"{user_dict[new_user]}")
        rc = resp[0]
        self.assertIsNotNone(rc)
        if rc != 200:
            self.assertIsNotNone(None, f"删除用户{new_user}失败")
        self.logger.info(f"删除用户成功:\n{json.dumps(resp[1], indent=4, ensure_ascii=False)}")

    # 测试结束后恢复环境
    def post_test_case(self):

        resp = self.request.delete_session(self.session_id)
        self.assertIsNotNone(resp[0], "清除Token失败")
        self.logger.info("清除Token成功")
